/*************************************************************************
	> File Name: tcp_chat_client.c
	> Author: ma6174
	> Mail: ma6174@163.com 
	> Created Time: Fri 29 Jul 2016 07:02:38 PM CST
 ************************************************************************/

#include"common.h"
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<sys/time.h>

int main(void)
{
	int ssfd;
	ssfd = socket(AF_INET, SOCK_STREAM,  0);
	if(ssfd < 0)
		err_sys("ss socket error");

	struct sockaddr_in dst_addr;
	bzero(&dst_addr, sizeof(dst_addr));
	dst_addr.sin_family = AF_INET;
	dst_addr.sin_port = htons(8888);
	inet_pton(AF_INET, "127.0.0.1", &dst_addr.sin_addr.s_addr);

	int ret;
	ret = connect(ssfd, (struct sockaddr*)&dst_addr, sizeof(dst_addr));
	if(ret != 0)
	{
		printf("Please turn on the server!\n");
		err_sys("ss connect error");
	}

	char send_buf[1024];
	char recv_buf[1024];

	int stdin_eof = 0;
	int maxssfd = ssfd + 1;
	fd_set read_set;
	FD_ZERO(&read_set);
	while(1)
	{
		printf("*********************************\n");
		printf("input your cmd:\n1, printf ——打印当前在线用户\n2, delelte name ——强制某用户下线\n3, stop ——关闭ss程序\n");
                printf("4, p_level 0~1 ——设置打印级别\n   打印级别详情：\n   level 0 为打印提示信息\n   level 1 为打印错误信息\n");
        printf("*********************************\n");
		if(stdin_eof == 0)
		{
			FD_SET(0, &read_set);
		}
		FD_SET(ssfd, &read_set);
		select(maxssfd, &read_set, NULL, NULL, NULL);
		if(FD_ISSET(0, &read_set))
		{
			fgets(send_buf, 1024, stdin);
			printf("send_buf:%s", send_buf);
			if(strncmp(send_buf, "stop", strlen("stop")) == 0)
			{
				send(ssfd, send_buf, strlen(send_buf), 0);
				stdin_eof = 1;
				shutdown(ssfd, SHUT_WR);
				FD_CLR(0, &read_set);
				send(ssfd, send_buf, strlen(send_buf), 0);
				memset(&send_buf, 0, sizeof(send_buf));
				continue;
			}
			send(ssfd, send_buf, strlen(send_buf), 0);
			memset(&send_buf, 0, sizeof(send_buf));
		}
		
		int i = 0;
		if(FD_ISSET(ssfd, &read_set))
		{
			if(i == 0)
			{
				printf("online users: \n");
				i++;
			}
			int ret;
			ret = recv(ssfd, recv_buf, strlen(recv_buf), 0);
			if(ret == 0)
			{
				printf("server closed");
				break;
			}
			recv_buf[ret] = '\0';
			printf("%s\n", recv_buf);
		}
	}
	close(ssfd);
	return 0;
}
